import React, { useEffect, useState } from 'react';
import { WaitUmd, loc, Btn, KSwitch, useKForm, is_empty, Title, sn_name, Ret, PanelTitle, useCmd } from 'sui';
import { update_prop, reload_prop } from './cmd';

const AttrView = ({ hreturn, subtitle, cur, mod, attr, no_acc }) => {
    const [main, setMain] = useState();
    const umd = useCmd();
    const form = useKForm();

    useEffect(() => {
        reload_prop(null, v => setMain(v), mod, cur);
    }, [mod, cur]);

    useEffect(() => {
        if (is_empty(attr)) {
            return null;
        }

        form.setValue(main);

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [main, attr]);

    const hok = () => update_prop(umd, mod, form.value, cur, setMain, () => hreturn(true));

    const Left = () => <Title mod={sn_name(cur)} sub={subtitle} className="mr-32"/>;

    const getCtl = () => {
        if (is_empty(attr)) {
            return null;
        }

        return attr.map(d => <KSwitch key={d.sn} name={d.sn} form={form}>{d.name}</KSwitch>);
    };

    const Right = () => (
        <div className="flex-inline">
            <Ret hcmd={hreturn}/>
            <Btn color="green" className="ml-4" hcmd={hok} disabled={no_acc}>{loc("l_234")}</Btn>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelTitle cl="gray" left={<Left/>} right={<Right/>}/>
            <div className="mt-4 ml-4">
                {getCtl()}
            </div>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {AttrView};
